
// 用栈来解决
function largestRectangleArea(heights) {
    if(!heights || heights.length === 0){
        return 0;
    }
    if(heights.length === 1){
        return heights[0];
    }
    elements =[0].concat(heights).concat(0);
    let stack = [];
    let maxArea = 0
    for (let i = 0; i < elements.length; i++) {
        const curr = elements[i];
        if(stack.length === 0){
            stack.push({
                value: curr,
                id: i
            });
            continue;
        }
        let stackTop = stack[stack.length-1];
        while(curr < stackTop.value){
            stack.pop();
            stackSecond = stack[stack.length-1];
            // 这里减去1，是数学的处理，当前计算这个元素的左边界和有边界差值，减去1才是它真正的宽度
            maxArea = Math.max(maxArea, stackTop.value * (i - stackSecond.id - 1))
            // 重新设置stackTop用于循环条件的判断
            stackTop = stackSecond
        }
        stack.push({
            value: curr,
            id: i
        })
    }
    return maxArea
}

console.log(largestRectangleArea([1,2,0]))